﻿//
// Created by 37616 on 2025/11/9.
//

#include "../include/API.h"
#include <cpr/cpr.h>
#include <iostream>

const std::string base_url = "https://fq.shusan.cn";

std::vector<Novel> search_novel(const std::string &keyword, int offset, int _tab) {
    std::vector<Novel> novels;
    //搜索接口路径
    std::string search_url = base_url + "/api/search";
    auto headers = cpr::Header{
        {
            "User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.52"
        },
        {"Accept", "application/json"}
    };
    //请求负载
    auto params = cpr::Parameters{
        {"key", keyword}, {"tab_type", std::to_string(_tab)}, {"offset", std::to_string(offset)}
    };
    //请求
    cpr::Response res = cpr::Get(cpr::Url{search_url}, params, headers);
    if (res.status_code != 200) {
        std::cerr << "搜索请求失败，HTTP状态码: " << res.status_code << std::endl;
        std::cerr << "错误信息: " << res.error.message << std::endl;
        return novels;
    }

    try {
        nlohmann::json json_data = nlohmann::json::parse(res.text);
        auto code = json_data["code"];
        if (code != 200) {
            std::cerr << "API返回错误: " << json_data.value("message", "未知错误") << std::endl;
            return novels;
        }
        for (const auto &tab: json_data["data"]["search_tabs"]) {
            int tab_type = tab.value("tab_type", 0);
            if (tab_type == 3 && tab.contains("data") && !tab["data"].is_null()) {
                for (const auto &item: tab["data"]) {
                    const auto &book_data = item["book_data"][0];
                    Novel novel;
                    novel.abstract = book_data["abstract"];
                    novel.author = book_data["author"];
                    novel.book_id = book_data["book_id"];
                    novel.book_name = book_data["book_name"];
                    novels.push_back(novel);
                }
            }
        }
    } catch (const nlohmann::json::parse_error &e) {
        std::cerr << "JSON解析错误: " << e.what() << std::endl;
    } catch (const std::exception &e) {
        std::cerr << "发生错误: " << e.what() << std::endl;
    }
    return novels;
}

void display_novels(const std::vector<Novel> &novels) {
    if (novels.empty()) {
        std::cout << "未找到相关小说" << std::endl;
        return;
    }

    std::cout << "\n📚 搜索结果 (共 " << novels.size() << " 本):\n" << std::endl;
    std::cout << "================================================================" << std::endl;

    for (size_t i = 0; i < novels.size(); ++i) {
        const auto &novel = novels[i];

        std::cout << i + 1 << ". 《" << novel.book_name << "》" << std::endl;
        std::cout << "   作者: " << novel.author << std::endl;
        std::cout << "   ID: " << novel.book_id << std::endl;

        // 显示简介（简洁版）
        if (!novel.abstract.empty()) {
            // 如果简介太长，截取前80个字符
            if (novel.abstract.length() > 80) {
                std::cout << "   简介: " << novel.abstract.substr(0, 80) << "..." << std::endl;
            } else {
                std::cout << "   简介: " << novel.abstract << std::endl;
            }
        }
        std::cout << "----------------------------------------" << std::endl;
    }
}

std::vector<Chapter> get_novel_chapter(const std::string book_id) {
    std::vector<Chapter> chapters;
    //目录接口
    std::string chapter_url = base_url + "/api/directory";
    auto headers = cpr::Header{
        {
            "User-Agent",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.52"
        },
        {"Accept", "application/json"}
    };
    //请求负载
    auto params = cpr::Parameters{
        {"book_id", book_id}
    };
    //请求发起
    cpr::Response res = cpr::Get(cpr::Url{chapter_url}, params, headers);
    if (res.status_code != 200) {
        std::cerr << "获取目录失败，HTTP状态码: " << res.status_code << std::endl;
        std::cerr << "错误信息: " << res.error.message << std::endl;
        return chapters;
    }
    try {
        nlohmann::json json_data = nlohmann::json::parse(res.text);
        auto code = json_data["code"];

        if (code != 200) {
            std::cerr << "API返回错误: " << json_data.value("message", "未知错误") << std::endl;
            return chapters;
        }

        if (json_data["data"].contains("lists")) {
            for (const auto &chapter_item: json_data["data"]["lists"]) {
                Chapter chapter;
                chapter.chapter_id = chapter_item.value("item_id", "");
                chapter.title = chapter_item.value("title", "");
                chapters.push_back(chapter);
            }
        }

        std::cout << "成功获取 " << chapters.size() << " 个章节" << std::endl;
    } catch (const nlohmann::json::parse_error &e) {
        std::cerr << "JSON解析错误: " << e.what() << std::endl;
    } catch (const std::exception &e) {
        std::cerr << "发生错误: " << e.what() << std::endl;
    }
    return chapters;
}
